import { getMenus, login } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: JSON.parse(localStorage.getItem('userInfo')) || {}
}

const mutations = {
  setToken(state, newToken) {
    // 存token 到vuex
    state.token = newToken
    // 存token到本地
    setToken(newToken)
  },
  // 用户信息
  getUserInfo(state, newInfo) {
    state.userInfo = newInfo
    localStorage.setItem('userInfo', JSON.stringify(newInfo))
  }
}

const actions = {
  // 登录请求
  async login(context, payload) {
    const res = await login(payload)
    // console.log(res)
    context.commit('setToken', res.data.token.token)
    // 用户信息
    context.commit('getUserInfo', res.data.user)
  },
  // 清空tokne 和 用信息
  logout(context) {
    context.commit('setToken', '')
    context.commit('getUserInfo', {})
  },
  // 侧边栏
  async getMenus() {
    const res = await getMenus()
    console.log(res)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

